package sg.edu.nus.comp.cs4218.impl.fileutils;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import sg.edu.nus.comp.cs4218.fileutils.ILsTool;
import sg.edu.nus.comp.cs4218.impl.ATool;

public class LsTool extends ATool implements ILsTool {

	/**
	 * Constructor
	 * 
	 */
	public LsTool() {
		super((String [])null);
		setStatusCode(0);
	}
	/**
	 * Constructor
	 * 
	 * @param arguments
	 *            - Arguments the tool is going to be executed with.
	 */
	public LsTool(String[] arguments)	{
		super(arguments);
		setStatusCode(0);
	}

	/**
	 * Retrieves the list of objects from the current working directory
	 * 
	 * @param directory
	 *            - The current working directory
	 * @return An array list of the contents of the current working directory
	 */
	@Override
	public List<File> getFiles(File directory) {

		// Error Handling
		if (directory == null || !directory.exists()
				|| !directory.isDirectory()) {
			setStatusCode(1);
			return null;
		}
		// Processing the Command
		return new ArrayList<File>(Arrays.asList(directory.listFiles()));
	}

	/**
	 * Converts the list of object into a string representation of the objects'
	 * names
	 * 
	 * @param files
	 *            - An array list of the contents of the current working directory
	 * @return A string representation of the objects' names
	 */
	@Override
	public String getStringForFiles(List<File> files) {
		// Error Handling
		if (getStatusCode() != 0) {
			return "Error: Unable to access working directory";
		}

		// Converts the list of object into a string representation of the
		// objects' names
		String fileString = null;

		for (File file : files) {
			if (fileString == null) {
				fileString = file.getName() + "\n";
			} else {
				fileString = fileString + file.getName() + "\n";
			}
		}
		fileString = fileString + files.size() + " item(s) in directory";

		return fileString;
	}

	/**
	 * Retrieves the contents of the current working directory
	 * 
	 * @param stdin
	 *            - Input on stdin. NOT THE ARGUMENTS! Can be null.
	 * @return Output on stdout
	 */
	@Override
	public String execute(File workingDir, String stdin) {
		return getStringForFiles(getFiles(workingDir));
	}
}
